"use client";

import type { Notice } from "@/lib/api/system/notice.d";
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
  ProTableProps,
} from "@ant-design/pro-components";
import { Button, message, Popconfirm, Space, Tag } from "antd";
import { useRouter } from "next/navigation";
import { useRequest } from "ahooks";
import { useRef } from "react";
import { deleteNoticeApi, getNoticeListApi } from "@/lib/api/system/notice";
import { getDictDatasByTypesApi } from "@/lib/api/system/dict";
import { getDictValueEnum } from "@/lib/utils/dict";

export default function Notice() {
  const router = useRouter();
  const actionRef = useRef<ActionType>();

  const { data: dictData } = useRequest(() =>
    getDictDatasByTypesApi(["sys_notice_status", "sys_notice_type"]),
  );

  const [status, type] = dictData ?? [[], []];

  const { run: deleteNotice } = useRequest(deleteNoticeApi, {
    manual: true,
    onSuccess: () => {
      message.success("删除成功");
      actionRef.current?.reload();
    },
    onError: () => {
      message.error("删除失败");
    },
  });

  const colums: ProColumns<Notice>[] = [
    {
      title: "公告标题",
      dataIndex: "noticeTitle",
      key: "noticeTitle",
    },
    {
      title: "公告类型",
      dataIndex: "noticeType",
      key: "noticeType",
      valueEnum: () => getDictValueEnum(type),
      render: (_, record) => {
        const item = type.find((item) => item.dictValue === record.noticeType);
        return item ? <Tag color="blue">{item.dictLabel}</Tag> : "-";
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      hideInSearch: true,
      valueEnum: () => getDictValueEnum(status),
      render: (_, record) => {
        const color = record.status === "0" ? "green" : "red";
        const item = status.find((item) => item.dictValue === record.status);
        return item ? <Tag color={color}>{item.dictLabel}</Tag> : "-";
      },
    },
    {
      title: "创建者",
      dataIndex: "createByName",
      hideInSearch: true,
      key: "createByName",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      valueType: "dateTime",
      width: 150,
      hideInSearch: true,
    },
    {
      title: "操作",
      key: "action",
      search: false,
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => editHandler(record.noticeId)}>
            修改
          </Button>
          <Popconfirm
            title="确定删除吗？"
            description="删除后将无法恢复！"
            onConfirm={() => {
              deleteNotice(record.noticeId);
            }}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const proTableProps: ProTableProps<Notice, any> = {
    columns: colums,
    rowKey: "noticeId",
    pagination: false,
    headerTitle: "通知列表",
    expandable: {
      defaultExpandAllRows: true,
    },
    actionRef: actionRef,
    options: {
      fullScreen: true,
    },
    toolBarRender: () => {
      return [
        <Button onClick={() => addHandler()} key="add" type="primary">
          新增
        </Button>,
      ];
    },
    request: async (params) => {
      const res = await getNoticeListApi(params);

      return {
        data: res.rows,
        success: true,
        total: res.total,
      };
    },
    onRequestError(e) {
      message.error(e.message);
    },
  };

  const addHandler = (noticeId?: string) => {
    router.push(`notice/add?noticeId=${noticeId}`);
  };

  const editHandler = (noticeId: string) => {
    router.push(`notice/edit?noticeId=${noticeId}`);
  };

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <ProTable {...proTableProps}></ProTable>
    </PageContainer>
  );
}
